#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网页截图推送到企业微信 - HTTP API服务
"""

from flask import Flask, request, jsonify
import os
from webpage_to_wechat import WebPageToWeChat

app = Flask(__name__)

# 默认配置
DEFAULT_WEBHOOK_URL = os.getenv(
    'DEFAULT_WEBHOOK_URL',
    'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=36fbd2fa-3796-43a4-b8dc-b953faf08645'
)
DEFAULT_TARGET_URL = os.getenv(
    'DEFAULT_TARGET_URL',
    'http://devops.derucci.smart/outside/agents/reportView'
)


@app.route('/health', methods=['GET'])
def health():
    """健康检查接口"""
    return jsonify({
        'status': 'ok',
        'message': 'Service is running'
    })


@app.route('/screenshot', methods=['POST'])
def screenshot_default():
    """
    使用默认配置截图并发送到企业微信
    
    POST /screenshot
    Body: {
        "wait_time": 15,  // 可选，等待时间（秒）
        "width": 1200,    // 可选，截图宽度
        "full_page": true // 可选，是否全页面截图
    }
    """
    try:
        data = request.get_json() or {}
        
        wait_time = data.get('wait_time', 15)
        width = data.get('width', 1200)
        full_page = data.get('full_page', True)
        
        # 创建实例
        bot = WebPageToWeChat(DEFAULT_WEBHOOK_URL)
        
        # 截图
        screenshot_path = bot.capture_webpage(
            DEFAULT_TARGET_URL,
            wait_time=wait_time,
            width=width,
            full_page=full_page
        )
        
        # 发送到企业微信
        result = bot.send_image_to_wechat(screenshot_path)
        
        return jsonify({
            'success': True,
            'message': '截图并发送成功',
            'screenshot_path': screenshot_path,
            'wechat_response': result
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'错误: {str(e)}'
        }), 500


@app.route('/screenshot/custom', methods=['POST'])
def screenshot_custom():
    """
    使用自定义配置截图并发送到企业微信
    
    POST /screenshot/custom
    Body: {
        "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
        "target_url": "https://example.com",
        "wait_time": 15,  // 可选
        "width": 1200,    // 可选
        "full_page": true // 可选
    }
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'message': '请求体不能为空'
            }), 400
        
        webhook_url = data.get('webhook_url')
        target_url = data.get('target_url')
        
        if not webhook_url or not target_url:
            return jsonify({
                'success': False,
                'message': 'webhook_url 和 target_url 是必填参数'
            }), 400
        
        wait_time = data.get('wait_time', 15)
        width = data.get('width', 1200)
        full_page = data.get('full_page', True)
        
        # 创建实例
        bot = WebPageToWeChat(webhook_url)
        
        # 截图
        screenshot_path = bot.capture_webpage(
            target_url,
            wait_time=wait_time,
            width=width,
            full_page=full_page
        )
        
        # 发送到企业微信
        result = bot.send_image_to_wechat(screenshot_path)
        
        return jsonify({
            'success': True,
            'message': '截图并发送成功',
            'screenshot_path': screenshot_path,
            'wechat_response': result
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'错误: {str(e)}'
        }), 500


@app.route('/screenshot/only', methods=['POST'])
def screenshot_only():
    """
    只截图不发送到企业微信
    
    POST /screenshot/only
    Body: {
        "target_url": "https://example.com",
        "wait_time": 15,  // 可选
        "width": 1200,    // 可选
        "full_page": true // 可选
    }
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'message': '请求体不能为空'
            }), 400
        
        target_url = data.get('target_url')
        
        if not target_url:
            return jsonify({
                'success': False,
                'message': 'target_url 是必填参数'
            }), 400
        
        wait_time = data.get('wait_time', 15)
        width = data.get('width', 1200)
        full_page = data.get('full_page', True)
        
        # 创建实例（webhook_url可以为空）
        bot = WebPageToWeChat('')
        
        # 截图
        screenshot_path = bot.capture_webpage(
            target_url,
            wait_time=wait_time,
            width=width,
            full_page=full_page
        )
        
        return jsonify({
            'success': True,
            'message': '截图成功',
            'screenshot_path': screenshot_path
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'错误: {str(e)}'
        }), 500


if __name__ == '__main__':
    port = int(os.getenv('PORT', 35511))
    app.run(host='0.0.0.0', port=port, debug=False)
